<template>
  <div>
    <h3>{{id?'编辑':'新建'}}商品</h3>
    <el-form label-width="60px" @submit.native.prevent="save">
      <el-tabs value="second" type="border-card">
        <el-tab-pane label="产品信息" name="first">
          <el-form-item label="名称">
            <el-input v-model="model.name"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="price"></el-input>
          </el-form-item>
          <el-form-item label="积分">
            <el-input v-model="model.point"></el-input>
          </el-form-item>
          <el-form-item label="库存">
            <el-input v-model="model.sum"></el-input>
          </el-form-item>
          <el-form-item label="权重">
            <el-input step="1" v-model="model.power" type="number"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="model.state"
              active-text="上线"
            />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="产品轮播" name="second">
          <el-form-item label="轮播">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              :action="$axios.defaults.baseURL+'upload_json.php'"
              :auto-upload="false"
              name="imgFile"
              :limit="5"
              :on-success="afterUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="imgRemove"
              list-type="picture-card"
              :file-list="model.imgs"
              accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PNG, .GIF, .BMP"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="富文本信息" name="third">
          <vue-editor
            v-model="model.info"
            useCustomImageHandler
            @image-added="handleImageAdded"
            style="margin:15px auto"
          ></vue-editor>
        </el-tab-pane>
      </el-tabs>
      <el-form-item style="margin-top:10px">
        <el-button type="primary" native-type="submit">{{id?'更新':'创建'}}</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
export default {
  props: {
    id: {}
  },
  watch: {
    price(val) {
      this.model.CNY = val * 100;
    }
  },
  components: {
    VueEditor
  },
  data() {
    return {
      model: {
        token: sessionStorage.token,
        table: "items",
        name: "",
        CNY: 0,
        point: 0,
        sum: 0,
        info: "",
        img: "",
        imgs: [],
        timeout: 60000,
        state: false,
        power: 0
      },
      price: 0
    };
  },
  methods: {
    cancel() {
      // console.log(this.$cp(this.model));
    },
    imgupload(a) {
      if (a.url) {
        this.model.img = this.$axios.defaults.baseURL + a.url.substr(1);
      }
    },
    fetch() {
      const info = {
        cmd: 0,
        val: {
          token: sessionStorage.token,
          table: "items",
          ID: this.id
        }
      };
      this.$axios.post("q.php", info).then(res => {
        if (res.data.result) {
          res.data.result.formatData();
          this.model = res.data.result[0];
          this.price = this.model.CNY / 100;
          // console.log(this.$cp(this.model));
        }
      });
    },
    // Form表单保存
    mesIF(res) {
      
      if (res.data.result) {
        this.$message({
          type: "success",
          message: "添加成功"
        });
        this.$router.push("/product/list");
      } else {
        this.$message({
          type: "danger",
          message: "添加失败"
        });
      }
    },
    save() {
      let res = this.$refs.upload.uploadFiles;
      for (let i = 0; i < res.length; i++) {
        if (res[i].status != "success") {
          this.$refs.upload.submit();
          return;
        }
      }
      // let tmp = this.$api.length;
      // res = this.$cp(this.model.imgs, ["url"]).map(a => {
      //   return { url: a.url.substr(tmp) };
      // });
      const info = { cmd: this.id ? 1 : 2, val: {} };
      info.val = this.$del(this.model);
      info.val.token = sessionStorage.token;
      info.val.table = "items";
      if (this.id) info.val.where = { ID: this.model.ID };
      // console.log(this.$cp(info.val));
      this.$axios.post("q.php", info).then(res => {
        // console.log(res.data);
        this.mesIF(res);
      });
    },
    //表单图片处理
    //封面
    afterUpload(a, b, c) {
      if (a.error) {
        this.$message.error("不支持此类文件");
        this.handleRemove(b);
      } else {
        this.$message.success(b.name + "上传成功");
        for (const i in this.$refs.upload.uploadFiles) {
          if (this.$refs.upload.uploadFiles[i].uid == b.uid)
            this.$refs.upload.uploadFiles[i].url = this.$api + a.url;
        }
        this.model.imgs = this.$cp(this.$refs.upload.uploadFiles);
      }
      for (const j in c) {
        if (c[j].status == "ready" || c[j].status == "uploading") return;
      }
      this.$message.success("全部上传成功!");
      this.save();
    },
    imgRemove(file) {
      let tmp = false;
      if (file.response && !file.response.error) tmp = file.response.url;
      if (file.url.substr(0, 5) != "blob:") tmp = file.url;
      if (file.url.substr(0, 1) != "/") tmp = file.url.substr(this.$api.length);
      if (tmp) this.$axios.post("upload_json.php", "del=" + tmp);
      this.model.imgs = this.$cp(this.$refs.upload.uploadFiles);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 富文本编辑器图片处理
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      let formData = new FormData();
      formData.append("imgFile", file);

      this.$axios.post("upload_json.php", formData).then(res => {
        console.log(res.data);
        Editor.insertEmbed(
          cursorLocation,
          "image",
          this.$axios.defaults.baseURL + res.data.url.substr(1)
        );
        resetUploader();
      });
    }
  },
  created() {
    this.id && this.fetch();
    // console.log(this.$cp(this.model));
  }
};
</script>

<style lang="scss">
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  min-width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>